<template>
  <div class="app-container">
    <el-page-header @back="goBack" content="模版"> </el-page-header>
    <h3></h3>
    <el-row>
      <el-col :span="7">
        <el-form ref="baseInfo" :rules="baseInfoRules" :model="baseInfo">
          <el-form-item prop="temp_name" :label-width="labelWidth" label="名称">
            <el-input
              style="width: 400px"
              placeholder="请输入模版名称"
              v-model="baseInfo.temp_name"
            ></el-input>
          </el-form-item>
          <el-form-item prop="temp_id" :label-width="labelWidth" label="模版id">
            <el-select
              filterable
              @change="tempSelect"
              style="width: 400px"
              v-model="baseInfo.temp_id"
              placeholder="请选择"
            >
              <el-option
                v-for="item in tempList"
                :key="item.template_id"
                :label="item.title"
                :value="item.template_id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="status"
            :label-width="labelWidth"
            label="是否启用"
          >
            <el-radio-group v-model="baseInfo.status">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label-width="labelWidth" label="跳转链接">
            <el-input
              style="width: 400px"
              placeholder="请输入跳转链接"
              v-model="baseInfo.url"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <!-- <h4 style="color: red">注意事项</h4>
          <p style="color: red">
            模版消息中尽量少出现引导粉丝点击，推广营销等其他与当前模版消息无关信息之类的,否则微信官方将会限制你的模版消息，无法正常发送
          </p> -->
        <div v-html="tip"></div>
      </el-col>
    </el-row>
    <template v-if="Object.keys(curTemp).length">
      <h4>模版示例</h4>
      <div style="display: flex">
        <div
          class="left"
          style="
            white-space: pre-line;
            border: 1px solid #dbdbdb;
            padding: 10px;
          "
          v-html="curTemp.example"
        ></div>
        <div class="right" style="flex: 1">
          <div class="item">
            <span class="label">模版ID</span>
            <span>{{ curTemp.template_id }}</span>
          </div>
          <div class="item" style="margin: 15px 0">
            <span class="label">标题</span>
            <span>{{ curTemp.title }}</span>
          </div>
          <!-- {{ setList }} -->
          <div class="">
            <div class="label" style="margin-bottom: 10px">详细内容</div>
            <!-- <span style="white-space: pre-line">{{ curTemp.content }}</span> -->
            <div
              style="margin-bottom: 10px"
              v-for="(item, index) in setList"
              :key="index"
            >
              <div style="display: flex; align-items: center">
                <span
                  style="width: 200px; text-align: right; margin-right: 10px"
                  >{{ item.label }}</span
                >
                <!-- [getText(item.text, index).field] -->
                <el-input
                  placeholder="请输入:"
                  v-model="item.value"
                  style="width: 600px"
                ></el-input>
                <div style="margin-left: 10px">
                  <el-color-picker v-model="item.color"></el-color-picker>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <!-- <h5>
      <el-button type="primary" icon="Plus" @click="addParams"
        >添加参数</el-button
      >
    </h5> -->
    <h3>参考</h3>
    <x-table :tableData="baseInfo.data" :propList="propList">
      <!-- <template #op="scope">
        <el-button type="primary"
link icon="Edit" @click="edit(scope.row)"
          >编辑</el-button
        >
        <el-button
          type="primary"
link
          icon="Delete"
          @click="del(scope.row, scope.index)"
          >删除</el-button
        >
      </template> -->
    </x-table>
    <h3 style="text-align: center">
      <el-button style="width: 150px" type="success" @click="submit"
        >提交</el-button
      >
    </h3>
    <h4>系统变量</h4>
    <span>时间</span>
    <div style="display: flex; background-color: #f5f5f5; padding: 20px">
      <div>{now}：当前时间</div>
    </div>
    <span>平台系统相关</span>
    <div style="display: flex; background-color: #f5f5f5; padding: 20px">
      <div class="env-item">{sys_user_name}：当前系统商户的名称</div>
      <div class="env-item">{sys_user_id}：当前系统商户的ID</div>
      <div class="env-item">{sys_user_balance}：当前系统商户的余额</div>
      <div class="env-item">{sys_user_credit}：当前系统商户的授信</div>
    </div>
    <h3></h3>
    <span>订单相关</span>
    <div
      style="
        display: flex;
        flex-wrap: wrap;
        background-color: #f5f5f5;
        padding: 20px;
        flex
      "
    >
      <!-- <div class="env-item">{cate_title}：分类名称</div> -->
      <div class="env-item">{goods_title}：产品名称(产品分类+面值)</div>
      <div class="env-item">{order_mobile}：下单手机号</div>
      <!-- <div class="env-item">{order_account}：下单帐号</div> -->
      <div class="env-item">{order_price}：下单金额</div>

      <div class="env-item">{movies_name}:电影名称</div>
      <div class="env-item">{movies_count}:电影票数量</div>
      <div class="env-item">{room_name}:影厅</div>
      <div class="env-item">{cinema_name}:影院名称</div>
      <div class="env-item">{show_time}:放映时间</div>
      <div class="env-item">{play_remain_time}:开场剩余时间</div>
      <div class="env-item">{seat_data_str}:购买电影票的座位</div>

      <div class="env-item">{order_sn}：订单号</div>
      <!-- <div class="env-item">{profit}：利润</div> -->
      <div class="env-item">{order_created_at}：下单时间</div>
      <div class="env-item">{order_status}：订单状态</div>
      <div class="env-item">{order_remark}：订单备注</div>
      <div class="env-item">{order_end_time}：订单结算时间</div>
      <div class="env-item">{order_nickname}：下单用户昵称</div>
      <div class="env-item">{face_val}：面值</div>
    </div>
    <h3></h3>
    <span>分销相关</span>
    <div
      style="
        display: flex;
        justify-content: space-around;
        background-color: #f5f5f5;
        padding: 20px;
      "
    >
      <div>{nickname}：昵称</div>
      <!-- <div>{child_nickname}：当前付款的下级昵称（可能为一级或二级）</div> -->
      <div>{bind_nickname_id}：绑定粉丝的ID</div>
      <div>{bind_nickname}：绑定粉丝的昵称</div>
      <div>{leavel}：当前等级</div>
      <div>{get_money}：收益金额</div>
    </div>
    <h3></h3>
    <span>(提现)金额相关</span>
    <div
      style="
        display: flex;
        justify-content: space-around;
        background-color: #f5f5f5;
        padding: 20px;
      "
    >
      <div>{user_money}：当前余额</div>
      <!-- <div>{money}：当前余额</div> -->
      <div>{tx_money}：当前提现金额</div>
      <div>{tx_created_at}：提现申请时间</div>
      <div>{tx_wx_num}：提现微信号</div>
      <div>{tx_fail_text}：提现失败原因</div>
    </div>
    <span>投诉建议变量</span>
    <div style="display: flex; background-color: #f5f5f5; padding: 20px">
      <div class="env-item">{mobile}：粉丝在公众号输入的手机号</div>
      <div class="env-item">
        {con_str}：粉丝在公众号输入的投诉内容(超过100字显示省略号)
      </div>
      <div class="env-item">{nickname}：粉丝昵称</div>
    </div>
    <!-- v-drag  -->
    <el-dialog draggable title="模版参数" v-model="tempDialog">
      <el-form ref="tempForm" :model="tempForm" :rules="tempFormRules">
        <el-form-item prop="column" label="字段名称" :label-width="labelWidth">
          <el-input v-model="tempForm.column" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="value" label="内容" :label-width="labelWidth">
          <el-input v-model="tempForm.value" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="颜色" :label-width="labelWidth">
          <el-color-picker v-model="tempForm.color"></el-color-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="tempDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitTempParams">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getListFromWx, change, detail, add } from "@/api/mpManage/mpTemp";

export default {
  name: "mpmpTempadd",
  data() {
    return {
      tip: "",
      setList: [],
      curTemp: {},
      propList: [
        {
          label: "字段",
          prop: "column",
        },
        {
          label: "内容",
          prop: "value",
        },
        {
          label: "颜色",
          prop: "color",
        },
        // {
        //   label: "操作",
        //   slotName: "op",
        // },
      ],
      tempDialog: false,
      tempForm: {
        color: "#333",
      },
      tempFormRules: {
        column: [{ required: true, message: "请输入字段名" }],
        value: [{ required: true, message: "请输入内容" }],
      },

      tempList: [],
      labelWidth: "100px",
      baseInfo: {
        data: [],
        status: 1,
      },
      baseInfoRules: {
        temp_id: [{ required: true, message: "请选择模版" }],
        temp_name: [{ required: true, message: "请输入模版名称" }],
      },
      info: {},
      id: null,
      searchInfo: {
        page: 1,
        pageSize: 10,
      },
    };
  },
  computed: {},
  created() {
    this.id = this.$route.query.id;
    if (this.id) {
      this.getInfo();
    } else {
      this.init();
    }
  },
  mounted() {},
  methods: {
    init() {
      this.getListFromWx();
    },
    async getListFromWx() {
      const { data } = await getListFromWx();
      console.log(data);
      this.tip = data.tip;
      this.tempList = data.template_list;
      if (this.baseInfo.temp_id) {
        this.curTemp = this.tempList.find(
          (i) => i.template_id == this.baseInfo.temp_id
        );
        this.getSetList();
      }
    },
    submitTempParams() {
      this.$refs.tempForm.validate(async (valid) => {
        if (valid) {
          console.log(this.tempForm);
          if (this.tempForm.id) {
            // 修改
            const index = this.baseInfo.data.findIndex(
              (i) => i.id == this.tempForm.id
            );
            this.baseInfo.data.splice(index, 1, this.tempForm);
          } else {
            if (this.baseInfo.data.length) {
              this.tempForm.id =
                this.baseInfo.data[this.baseInfo.data.length - 1].id + 1;
            } else {
              this.tempForm.id = 1;
            }
            this.baseInfo.data.push({ ...this.tempForm });
          }

          this.tempDialog = false;
        }
      });
    },
    getText(item, index) {
      const str = item.text;
      const startIndex = str.indexOf("{{");
      const endIndex = str.indexOf(".DATA");
      const field = str.substring(startIndex + 2, endIndex);
      item.column = field;
      // console.log(field);
      let text = str.substring(0, startIndex);
      // console.log(startIndex, endIndex);
      if (!text) {
        text = "备注：";
        if (index == 0) {
          text = "头部标题：";
        }
      }
      return { field, text };
    },
    // 添加模版字段参数
    addParams() {
      if (Object.keys(this.curTemp).length == 0) {
        this.$message.error("请选择模版");
        return false;
      }
      console.log("addParams");
      this.tempForm = this.$options.data().tempForm;
      console.log(this.tempForm);
      this.tempDialog = true;
      this.$nextTick(() => {
        this.$refs.tempForm.clearValidate();
      });
    },
    async getInfo() {
      const { data } = await detail(this.id);
      data.data = JSON.parse(data.data);
      console.log(data.data);
      // this.setList = data.data;
      this.baseInfo = data;
      this.getListFromWx();
      //
    },
    tempSelect(val) {
      this.curTemp = this.tempList.find((item) => item.template_id == val);
      console.log("this.curTemp", this.curTemp);
      this.getSetList();
    },
    getSetList() {
      const tempArr = this.curTemp.content.split("\n");
      this.setList = [];
      tempArr.forEach((item) => {
        this.setList.push({
          text: item,
          color: "#333333", //默认颜色
        });
      });
      // console.log("baseInfo", this.baseInfo);
      this.setList.forEach((item, index) => {
        const { field, text } = this.getText(item, index);
        item.column = field;
        item.label = text;
        item.value = "";
        // console.log(item);
        if (this.baseInfo.data.length) {
          let activeItem = this.baseInfo.data.find((i) => {
            return i.column == field;
          });
          // console.log("activeItem", activeItem);
          if (activeItem) {
            item.value = activeItem.value;
            item.color = activeItem.color;
          }
        }
      });
    },
    submit() {
      this.$refs.baseInfo.validate(async (valid) => {
        if (valid) {
          console.log(this.baseInfo);
          const params = {
            ...this.baseInfo,
          };
          params.temp_title = this.curTemp.title;
          // params.data = JSON.stringify(params.data);
          params.data = JSON.stringify(this.setList);
          if (this.id) {
            params.id = this.id;
            await change(params);
          } else {
            await add(params);
          }
          this.$message.success("操作成功");
          this.$router.back();
        }
      });
    },
    edit(item) {
      console.log(item);
      this.tempDialog = true;
      this.tempForm = { ...item };
    },
    async del(item, index) {
      console.log(item, index);
      const alertRes = await this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      if (alertRes == "confirm") {
        this.baseInfo.data.splice(index, 1);
      }
      console.log(alertRes);
    },
    goBack() {
      this.$router.back();
    },
  },
};
</script>

<style lang="scss" scoped>
.right {
  margin-left: 30px;
}
.item {
  display: flex;
  .label {
    display: inline-block;
    width: 100px;
    text-align: left;
  }
}
.env-item {
  margin-bottom: 15px;
  margin-right: 20px;
}
</style>
